package com.oceansoft.core.common.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 网络相关
 * 
 * @author Administrator
 * 
 */
public final class NetUtil {
	public static String getLocalHostIPAddress() {
		String[] ips = getAllLocalHostIPAddress(false);
		if (ips.length > 0) {
			return ips[0];
		}
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			try {
				return InetAddress.getByName(null).getHostAddress();
			} catch (UnknownHostException ex) {
			}
		}
		return "localhost";
	}

	public static String[] getAllLocalHostIPAddress() {
		return getAllLocalHostIPAddress(true);
	}

	private static String[] getAllLocalHostIPAddress(boolean allIpFlag) {
		List<String> ips = new ArrayList<String>();
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
				Enumeration<InetAddress> netAddresses = ni.getInetAddresses();
				while (netAddresses.hasMoreElements()) {
					ip = (InetAddress) netAddresses.nextElement();

					if ((ip == null) || (ip.isLoopbackAddress()) || (ip.getHostAddress().indexOf(":") != -1))
						continue;
					String address = ip.getHostAddress();
					if (allIpFlag)
						ips.add(address);
					else
						return new String[] { address };
				}
			}
		} catch (Exception ignore) {
		}
		return ips.toArray(new String[0]);
	}

	public static String getHostIPAddress(String hostName) {
		try {
			return InetAddress.getByName(hostName).getHostAddress();
		} catch (UnknownHostException e1) {
		}
		return null;
	}

	public static String getLocalHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
			try {
				return InetAddress.getByName(null).getHostName();
			} catch (UnknownHostException e1) {
			}
		}
		return null;
	}

	public static String getHostName(String ipv4) {
		try {
			String[] ips = ipv4.split("[.]");
			if (ips.length == 4) {
				return InetAddress.getByAddress(
						new byte[] { (byte) Integer.parseInt(ips[0]), (byte) Integer.parseInt(ips[1]),
								(byte) Integer.parseInt(ips[2]), (byte) Integer.parseInt(ips[3]) })
						.getCanonicalHostName();
			}

		} catch (UnknownHostException e) {
		}

		return null;
	}

	public static void main(String[] args) throws UnknownHostException {
		System.out.println(getHostName("192.168.0.158"));
	}

	public static void closeQuietly(Socket socket) {
		if (socket == null)
			return;
		try {
			socket.close();
		} catch (IOException e) {
		}
	}
}
